import { isUndefined, _pick } from "mmb";
import { isSearchTerm } from "../../bg-enums/searchTerm";
import { AppCTX } from "../../types/koaExtend";
import {
  applyAfterSale,
  cancelAfterSale,
  sendAfterSaleReturnGoods,
  listAfterSaleItemsForC,
  listAfterSaleItemsForS,
  getAfterSaleBySerialNumber,
} from "../../service/afterSaleService";
import pageMW from "../../middleware/pager";
import Router from "koa-router";
const router = new Router();

// 创建售后单(申请售后)
router.post("/usr/afterSale", async (ctx: AppCTX, next) => {
  const {
    orderSerialNumber,
    type,
    afterSaleReason,
    remark,
    details,
  } = ctx.request.body;
  const { userId } = ctx;
  const afterSale = await applyAfterSale({
    userId,
    orderSerialNumber,
    type,
    afterSaleReason,
    remark,
    details,
  });
  ctx.body = afterSale;
});

// 取消售后申请
router.put(
  "/usr/afterSale/:afterSaleSerialNumber/cancel",
  async (ctx: AppCTX, next) => {
    const { afterSaleSerialNumber } = ctx.params;
    const { userId } = ctx;
    const afterSale = await cancelAfterSale({ afterSaleSerialNumber, userId });
    ctx.body = afterSale;
  }
);

// 售后单用户确认寄出
router.put(
  "/usr/afterSale/:afterSaleSerialNumber/confirmSend",
  async (ctx: AppCTX, next) => {
    const { afterSaleSerialNumber } = ctx.params;
    const { platformId, platformName, platformNo } = ctx.request.body;
    const { userId } = ctx;
    const afterSale = await sendAfterSaleReturnGoods({
      afterSaleSerialNumber,
      userId,
      platformId,
      platformName,
      platformNo,
    });
    ctx.body = afterSale;
  }
);

// 获取用户的售后单列表
router.get("/usr/afterSales", pageMW, async (ctx: AppCTX, next) => {
  const { userId, limit, offset, ts } = ctx;
  const { total, items } = await listAfterSaleItemsForC(userId, {
    limit,
    offset,
    ts,
  });
  ctx.body = {
    total,
    rows: items,
  };
});

// 获取用户推广订单的售后列表
router.get("/usr/afterSalesAsSpokesman", pageMW, async (ctx: AppCTX, next) => {
  const { userId, limit, offset, ts } = ctx;
  const { searchTerm, searchValue } = ctx.query;
  if (!isUndefined(searchTerm) && !isSearchTerm(searchTerm)) {
    ctx.throw(400, "invalid searchTerm");
  }
  const { total, items } = await listAfterSaleItemsForS(
    { userId, searchTerm, searchValue },
    {
      limit,
      offset,
      ts,
    }
  );
  ctx.body = {
    total,
    rows: items,
  };
});

// 获取售后单详情(用户视角)
router.get(
  "/usr/afterSale/:afterSaleSerialNumber",
  async (ctx: AppCTX, next) => {
    const { afterSaleSerialNumber } = ctx.params;
    const { userId } = ctx;

    const afterSale = await getAfterSaleBySerialNumber(afterSaleSerialNumber);
    if (isUndefined(afterSale)) {
      ctx.throw(400, "invalid afterSaleSerialNumber");
    }
    if (afterSale.userId !== userId) {
      ctx.throw(403, "no permit access to the aftersale");
    }

    ctx.body = afterSale;
  }
);

export default router;
